<template>
  <div id="main">
    <el-tabs v-model="active" type="border-card" @tab-click="handleClick">
      <el-tab-pane label="单摄像头" name="single" style="height: 100%">
        <video id="cam-0" class="centeredVideo" controls autoplay/>
        <div id="controller-0">
          <span class="url">URL: {{cam_0_url == null ? "null" : cam_0_url}}</span><br><br>
          <el-button type="primary" style="width: 120px" size="small" @click="openCam(0)" plain>连接摄像头</el-button>
          <el-button type="danger" style="width: 120px" size="small" @click="closeCam(0)" plain>关闭摄像头</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="四摄像头" name="quarter" style="height: 100%">
        <div id="cam1"></div>
        <div id="cam2"></div>
        <div id="cam3"></div>
        <div id="cam4"></div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import flv from 'flv.js'
  export default {
    name: "Realtime",
    data(){
      return {
          active: "single",
          http_flv_url: "http://127.0.0.1/live?app=demo&stream=",
          cams: [null, null, null, null]
      }
    },
    methods: {
      openCam(id) {
        // TODO 请求后端，申请访问视频流，如果成功，则构建播放器并播放视频，否则message提示打开摄像头失败
        this.cams[id] = flv.createPlayer({type: "flv", url: this.http_flv_url + id})
        var videoElement = document.querySelector("#cam-0")
        this.cams[id].attachMediaElement(videoElement)
        this.cams[id].load()
        this.cams[id].play()
      },
      closeCam(id) {
        if (this.cams[id] != null) {
          this.cams[id].pause()
          this.cams[id].unload()
          this.cams[id].destroy()
          this.cams[id] = null
        }
      }
    }
  }
</script>

<style scoped>
#main {
    margin-top: 15px;
}

.url {
  font-size: 12px;
}

#cam-0 {
    margin-top: 10px;
    margin-left: 10px;
    /* 480p */
    width: 854px;
    height: 480px;
}

#controller-0 {
  /* background-color: red; */
  position: relative;
  top: -480px;
  left: 880px;
  width: 280px;
  height: 100%;
}

</style>